<template>
  <div class="page">
    <main-card :title="detailData?.name" :crumbs="crumbs" :loading="loading">
      <template #tool-btn>
        <a-button type="primary" @click="exportFun">导出报告</a-button>
      </template>

      <div class="detail-body">
        <div class="header-content">
          <div class="header-left">
            <div class="time-section">
              <span class="label">创建时间</span>
              <span class="value"> {{ detailData?.createTime }} </span>
            </div>
            <span class="line"></span>
            <div class="time-section">
              <span class="label">评估耗时</span>
              <span class="value"> {{ detailData?.assessmentTime }} </span>
            </div>
          </div>
          <div class="time-section">
            <span class="label">任务状态</span>
            <span class="value"> {{ getTaskStatusItem(detailData?.status)?.name }} </span>
          </div>
        </div>
        <div class="detail-section">
          <div class="section-left">
            <div class="title">评估结果输出目录</div>
            <div class="content">
              <code-tree
                :class="codeTreeClass"
                :tree-data="(detailData?.resultTree as any[])"
                :default-path="(fileTree?.defultPath as string)"
                @on-select="handleToSelect"
              />
            </div>
          </div>
          <div class="section-center">
            <div class="title">预览界面</div>
            <div class="content">
              <!-- 预览代码 -->
              <div v-if="hasPic">
                <a-spin v-if="hasCode" :spinning="loadingShow" tip="加载中">
                  <p class="preview-text">{{ previewTxt }}</p>
                </a-spin>
                <default-graph v-else :show-img="false">
                  <template #title>
                    <h4 class="default-graph-title">无可展示代码</h4>
                  </template>
                </default-graph>
              </div>
              <!-- </div> -->
              <!-- 预览图片 -->

              <div v-else class="preview-image">
                <img :src="previewUrl" />
              </div>
            </div>
          </div>
          <div class="section-right">
            <div class="title">任务详情</div>
            <div class="content">
              <div class="info-list">
                <div v-for="(item, index) in taskDetail" :key="index" class="item">
                  <div class="label">{{ item.label }}</div>
                  <div>
                    <div v-if="item.label === '评估代码' && codeAreaShow" :title="item.value" class="value flex">
                      {{ detailData?.codeFileName }}
                      <div class="download-code" @click="downLoadCodeFile">下载</div>
                    </div>
                    <div v-else :title="item.value" class="value">{{ item.value }}</div>
                  </div>
                </div>
              </div>

              <!-- 测试集 -->
              <div class="test-set">
                <div class="header">测试集</div>
                <div class="data my-scrollbar">
                  <div v-for="(item, index) in detailData?.dataList" :key="index" :title="item" class="item">
                    <img src="@/assets/img/file-line.svg" alt="" />
                    <span>
                      {{ item }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main-card>
  </div>
  <line-export ref="lineExportRef" v-model:show="showLineExport" :loading="okBtnLoading" @submit="onLineExportSubmit" />

  <task-list-drawer />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import DefaultGraph from '@/components/DefaultGraph/index.vue'
  import LineExport from '@/components/LineExport/index.vue'
  import { modelEvaluationApi } from '@/services/api'
  import { dataCleaningApi, fetchDownload } from '@/services/api'
  import { waitLoading } from '@/utils'

  import TaskListDrawer from '../components/TaskListDrawer/index.vue'
  import { useTaskListDrawerStore } from '../components/TaskListDrawer/store'
  import { getSourceItem, getTaskStatusItem } from '../options'
  const taskListDrawerStore = useTaskListDrawerStore()

  const route = useRoute()
  const parentParams = route.params as any

  const crumbs = [{ name: '模型评估', path: '/model-evaluation/list' }, { name: '任务详情' }]
  const hasCode = ref(true)

  // 指标
  const normDetailsOptions = ref<Record<string, any>[]>([])
  // 获取评估指标
  const getNormDetailsOptions = async () => {
    const { data } = await modelEvaluationApi.getNormDetailsOptions()
    normDetailsOptions.value = data
    console.log('normDetailsOptions.value:', normDetailsOptions.value)
  }

  const codeAreaShow = ref<boolean>(false)
  /* 获取数据 */
  const { data: detailData, loading, runAsync: runGetData } = useRequest<any>(modelEvaluationApi.getDetailResult)
  const getData = async () => {
    const { data } = await runGetData({ taskId: parentParams.id })
    if (data.source === 2 || data.source === 3 || data.source === 0) {
      codeAreaShow.value = true
    }
    detailData.value = data
    taskDetail.value[0].value = data.name
    taskDetail.value[1].value = (data.modelType === 0 ? '模型管理' : '我收藏的公开模型') + ' / ' + data.modelName
    taskDetail.value[2].value = getSourceItem(data.source)?.label

    taskDetail.value[3].value = data.normDetails
  }

  // 导出
  const showLineExport = ref(false)
  const lineExportRef = ref<InstanceType<typeof LineExport>>()
  const exportFun = async () => {
    const { data } = await modelEvaluationApi.export({
      taskId: detailData.value.id,
      taskRecordId: detailData.value.taskRecordId
    })

    waitLoading(fetchDownload(data, detailData?.value.name), {
      loadingText: '数据准备中,请耐心等待...',
      errorText: '文件下载失败',
      successText: '文件下载成功'
    })
  }
  const { loading: okBtnLoading, runAsync: runOnlineExport } = useRequest(dataCleaningApi.onlineExport)
  const onLineExportSubmit = async (formState: any) => {
    await runOnlineExport({ taskId: detailData.value.id, bucketName: formState.name, bucketId: formState.value })
    showLineExport.value = false
    taskListDrawerStore.changeTaskListOptions({ open: true, key: '1' })
  }

  // 下载
  const downLoadCodeFile = async () => {
    const params = {
      taskId: detailData.value.id,
      taskRecordId: detailData.value.taskRecordId,
      operateType: 0
    }
    const { data } = await getFileContentData(params)

    const prefixToRemove = 'http://171.217.69.51:31673/'

    const newUrl = data.replace(prefixToRemove, '')
    waitLoading(fetchDownload('/minioCode/' + newUrl, detailData.value.codeFileName), {
      loadingText: '数据准备中,请耐心等待...',
      errorText: '文件下载失败',
      successText: '文件下载成功'
    })
  }
  // 文件树
  const fileTree = ref<any>({})
  const previewUrl = ref<string>('')
  const hasPic = ref<boolean>(true)
  const handleToSelect = async (key: string[], e: any) => {
    const postfix: string = e.node.name.split('.')?.slice(-1)[0]
    if (key.length && !e.selectedNodes[0].isDir) {
      loadingShow.value = true
      // txt、json、png、jpg、jpeg、py
      const paramsPic = {
        taskId: detailData.value.id,
        taskRecordId: detailData.value.taskRecordId,
        operateType: 1,
        path: e.selectedNodes[0].path
      }
      if (postfix === 'py' || postfix === 'txt' || postfix === 'json') {
        await queryTaskFile(paramsPic, 0) // 文件预览
      } else if (postfix === 'png' || postfix === 'jpg' || postfix === 'jpeg') {
        await queryTaskFile(paramsPic, 1) // 图片预览
      } else {
        message.error('该类型文件不支持预览')
      }
    }
  }
  // 获取代码文件下载地址
  const { runAsync: getFileContentData } = useRequest<any>(modelEvaluationApi.getTaskFile)
  const queryTaskFile = async (params: Record<string, any>, type: Number) => {
    const { data } = await getFileContentData(params)
    if (type === 0) {
      hasPic.value = true

      downloadTextFromURL(data)
    } else {
      hasPic.value = false
      console.log('图片预览', data)
      previewUrl.value = data
    }
  }
  const loadingShow = ref<boolean>(false)

  const previewTxt = ref<string>('')
  //预读文件
  const downloadTextFromURL = (url: string) => {
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error()
        }
        return response.text()
      })
      .then(text => {
        // 在这里处理下载的文本内容
        previewTxt.value = text
        loadingShow.value = false
      })
      .catch(error => {
        loadingShow.value = false
        hasCode.value = false
        console.error('Error downloading text:', error)
      })
  }

  // 获取任务详情
  const taskDetail = ref<Record<string, string>[]>([
    {
      label: '模型名称',
      value: ''
    },
    {
      label: '选择模型',
      value: ''
    },
    {
      label: '模型来源',
      value: ''
    },
    {
      label: '评估指标',
      value: ''
    },
    {
      label: '评估代码',
      value: ''
    }
  ])

  onMounted(() => {
    getNormDetailsOptions()
    getData()
  })
</script>

<style lang="less" scoped>
  .page {
    width: 100%;
  }

  .detail-body {
    // display: flex;
    height: 698px;
    background: #fff;
    border: 1px solid #e8e9eb;
    border-radius: 10px;

    .header-content {
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 24px;
      width: 100%;
      // height: 56px;
      border-bottom: 1px solid @mask1;

      .header-left {
        display: flex;

        .line {
          margin-top: 8px;
          margin-right: 16px;
          width: 1px;
          height: 20px;
          background-color: @border2;
        }
      }

      .time-section {
        margin-right: 24px;
        font-size: 14px;
        font-weight: 400;
        line-height: 35px;

        .label {
          margin-right: 16px;
          color: @text03;
        }

        .value {
          color: @text01;
        }
      }
    }

    .detail-section {
      display: flex;
      height: 100%;
      height: calc(698px - 56px);

      .section-center {
        padding: 24px;
        width: 816px;
        border-left: 1px solid #e8e9eb;
        border-right: 1px solid #e8e9eb;

        .preview-text {
          overflow-y: auto;
          // padding: 0 0 0 15px;
          height: 562px;
          text-align: left;
          white-space: pre-wrap;
        }

        .preview-image {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 594px;
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }

      .title {
        color: @text01;
        font-weight: 700;
      }

      .content {
        margin-top: 16px;
      }

      .section-left {
        padding: 24px;
        padding: 24px 12px;
        width: 200px;

        .title {
          padding: 0 12px;
        }

        .content {
          overflow: hidden;
          margin-top: 20px;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .radio-list {
          overflow: hidden;

          :deep(.ant-tree) {
            .ant-tree-switcher-noop {
              display: none;
              width: 176px;
            }

            :deep(.ant-tree-title) {
              display: block !important;
              overflow: hidden !important;
              width: 165px !important;
              text-overflow: ellipsis !important;
              white-space: nowrap !important;
            }

            :deep(.ant-tree-node-content-wrapper) {
              padding: 0 12px;
              height: 32px;
              color: rgba(0, 0, 0, 0.85);
              line-height: 32px;
            }

            .ant-tree-node-content-wrapper.ant-tree-node-selected {
              color: @text01 !important;
              font-weight: 700;
              background-color: @mask1 !important;
            }
          }
        }
      }

      .section-right {
        padding: 24px;
        flex: 1;

        .content {
          display: flex;
          height: 565px;
          flex-direction: column;

          .info-list {
            .item {
              display: flex;
              margin-bottom: 12px;
              height: 32px;
              line-height: 32px;
              color: @text02;

              .label {
                margin-right: 24px;
                width: 56px;
              }

              .value {
                overflow: hidden;
                padding: 0 8px;
                width: 230px;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-weight: 700;
              }
            }

            .download-code {
              margin-left: 8px;
              color: @link;
              cursor: pointer;
            }
          }

          .test-set {
            width: 100%;
            height: 100%;
            background: #fff;
            border: 1px solid #e8e9eb;
            border-radius: 4px;

            .header {
              line-height: 36px;
              padding-left: 16px;
              height: 38px;
              color: @text02;
              background: @background3;
              font-weight: 700;
              border-top: 1px solid @background5;
              border-bottom: 1px solid @background5;
            }

            .data {
              overflow-y: auto;
              height: 304px;

              .item {
                display: flex;
                align-items: center;
                padding: 8px 12px;
                height: 40px;
                border-bottom: 1px solid #ebebeb;

                span {
                  overflow: hidden;
                  width: 256px;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }

                img {
                  margin-right: 9px;
                  margin-left: 5px;
                  width: 14px;
                  height: 14px;
                }
              }

              .item:last-child {
                border-bottom: none;
              }
            }
          }
        }
      }
    }

    :deep(.ant-spin) {
      max-height: 100%;
    }
  }
</style>
